import { View, Text, Swiper, SwiperItem, Image, Navigator } from "@tarojs/components";
import Taro, { useLoad, useReachBottom } from "@tarojs/taro";
import "./index.scss";
import { useEffect, useState } from "react";
import ListItem from "../../components/list-item";
const banners = [
  require("../../images/banner1.webp"),
  require("../../images/banner2.webp"),
  require("../../images/banner3.webp"),
  require("../../images/banner4.webp"),
];
export default function Home() {
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)
  const [finished, setFinish] = useState(false)
  const fetchList = async () => {
    Taro.showLoading({
      title: '数据拼命加载中...'
    })
    setLoading(true)
    const resp = await Taro.request({
      url: "http://localhost:3000/list",
      data: {
        _page: page
      }
    });
    setLoading(false)
    Taro.hideLoading()
    setList(list.concat(resp.data));
  };

  useEffect(() => {
    fetchList();
  }, [page]);

  useReachBottom(() => {
    if(loading) return ;
    if(list.length >= 100)  {
      setFinish(true)
      return ;
    }
    setPage(page + 1)
  })

  return (
    <View className="home">
      {/* 轮播 */}
      <Swiper className="swiper" autoplay circular indicatorDots>
        {banners.map((v, i) => {
          return (
            <SwiperItem key={i}>
              <Image src={v} className="banner"></Image>
            </SwiperItem>
          );
        })}
      </Swiper>
      {/* 列表 */}
      <View className="list">
        {
          list.map((v, i) => {
            return <Navigator key={i} url={"/pages/detail/index?id=" + v.id}>
              <ListItem  v={v}></ListItem>
            </Navigator>
          })
        }
        {
          finished &&  <view className="pull-down-finish">
          没有更多数据了
        </view>
        }
      </View>
    </View>
  );
}
